package com.jboltai.util.http;

import com.jboltai.event.Event;
import com.jboltai.util.share.AIEventThreadShareData;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class SSEListener extends EventSourceListener {


    private Consumer<String> successHandler;

    private BiConsumer<Response, Throwable> failHandler;
    /**
     * 触发请求的事件
     */
    private Event triggerEvent;


    public SSEListener(Consumer<String> successHandler, BiConsumer<Response, Throwable> failHandler) {
        this.successHandler = successHandler;
        this.failHandler = failHandler;
    }
    public SSEListener(Event triggerEvent, Consumer<String> successHandler, BiConsumer<Response, Throwable> failHandler) {
        this.triggerEvent = triggerEvent;
        this.successHandler = successHandler;
        this.failHandler = failHandler;

    }


    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        super.onClosed(eventSource);
    }

    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        if (triggerEvent != null && triggerEvent.getThreadShareData() != null) {
            AIEventThreadShareData.setShareData(triggerEvent.getThreadShareData());
        }
        if (successHandler != null) {
            successHandler.accept(data);
        }
    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        if (triggerEvent != null && triggerEvent.getThreadShareData() != null) {
            AIEventThreadShareData.setShareData(triggerEvent.getThreadShareData());
        }
        if (failHandler != null) {
            failHandler.accept(response, t);
        }
    }

    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        super.onOpen(eventSource, response);
    }
}
